<?php
/**
 * User: zhangligang
 * Email: tzhang2450@163.com
 * Date: 2018/7/27
 * Time: 上午6:48
 */

namespace App\Services;


use App\Models\Teacher;
use App\Models\TeacherScore;
use App\Models\User;
use App\Models\Unit;

class UserService extends Service
{

    public static function getTeacherList($limit, $offset, $order = 'desc', $option = [])
    {
        $query = Teacher::select(['at_user.realname', 'at_user.number', 'at_teacher.id', 'at_teacher.gender', 'at_teacher.join_at', 'at_teacher.work_age', 'at_teacher.education_code', 'at_teacher.professional_title_code', 'at_teacher.updated_at', 'at_teacher.status'])->leftJoin('at_user', 'at_user.id', 'at_teacher.user_id');
        if (count($option) && count($option['query'])) {
            foreach ($option['query'] as $search) {
                $key = 'at_teacher.';
                if ($search['key'] == 'realname') {
                    $key = 'at_user.';
                }
                $key .= $search['key'];
                $query = $query->where($key, $search['operator'], $search['value']);
            }
        }
        $total = $query->count();
        $teachers = $query->orderBy('at_teacher.id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($teachers as $teacher) {
            $data[] = [
                'id' => $teacher->id,
                'rent_user_name' => $teacher->realname . '（' . $teacher->number . '）',
                'gender' => $teacher->gender,
                'join_age' => date('Y', strtotime($teacher->join_at)) . '（' . $teacher->work_age . '年）',
                'education' => education($teacher->education_code),
                'education_code' => $teacher->education_code,
                'professional_title_code' => $teacher->professional_title_code,
                'updated_at' => local_date($teacher->updated_at, 'Y-m-d H:i:s'),
                'status' => $teacher->status
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getTeacherDetail($id = 0, $uid = 0)
    {
        if ($id) {
            $teacher = Teacher::where('id', $id)->first();
        } else {
            $teacher = Teacher::where('user_id', $uid)->first();
        }

        if (!$teacher) {
            return [];
        }

        $user = User::where('id', $teacher->user_id)->first();
        $unit = Unit::where('id', $teacher->unit)->first();

        return [
            'data' => [
                'id' => $teacher->id,
                'realname' => $user->realname,
                'number' => $user->number,
                'gender' => $teacher->gender,
                'identity' => $teacher->identity,
                'mobile' => $teacher->mobile,
                'email' => $teacher->email,
                'unit' => $teacher->unit,
                'unit_name' => $unit ? $unit->name : '',
                'join_at' => $teacher->join_at == '0000-00-00 00:00:00' ? '' : local_date($teacher->join_at, 'Y-m'),
                'work_age' => $teacher->work_age,
                'capacity' => $teacher->capacity,
                'education' => education($teacher->education_code),
                'education_code' => $teacher->education_code,
                'degree_code' => $teacher->degree_code,
                'degree' => degree($teacher->degree_code),
                'education_profile' => $teacher->education_profile,
                'degree_profile' => $teacher->degree_profile,
                'job_type' => $teacher->job_type,
                'job_code' => $teacher->job_code,
                'job' => work_job($teacher->job_type, $teacher->job_code),
                'professional_title_code' => $teacher->professional_title_code,
                'professional_title_profile' => $teacher->professional_title_profile,
                'professional_title' => professional_title($teacher->professional_title_code),
                'professional_check' => $teacher->professional_check == '0000-00-00 00:00:00' ? '' : local_date($teacher->professional_check, 'Y-m'),
                'duty_on' => $teacher->duty_on == '0000-00-00 00:00:00' ? '' : local_date($teacher->duty_on, 'Y-m'),
                'duty_type' => $teacher->duty_type,
                'marriage' => $teacher->marriage,
                'marriage_profile' => $teacher->marriage_profile,
                'spouse_name' => $teacher->spouse_name,
                'spouse_unit' => $teacher->spouse_unit,
                'score' => $teacher->score,
                'remark' => $teacher->remark,
                'has_house' => $teacher->has_house,
                'house_profile' => $teacher->house_profile
            ]
        ];
    }

    public static function saveTeacher($data)
    {
        $teacher = new Teacher();
        if (array_key_exists('user_id', $data)) {
            $teacher = Teacher::where('user_id', $data['user_id'])->first();
        } else {
            $teacher->created_at = date('Y-m-d H:i:s', time());
        }
        if (array_key_exists('realname', $data)) {
            $user = User::where('id', $data['user_id'])->first();
            $user->realname = $data['realname'];
            $user->save();
            unset($data['realname']);
        }
        if ($data['education_code'] != $teacher->education_code) {
            $teacher->education_profile = '';
            $teacher->degree_profile = '';
        }
        if ($data['professional_title_code'] != $teacher->professional_title_code) {
            $teacher->professional_title_profile = '';
        }
        if ($data['marriage'] != $teacher->marriage) {
            $teacher->marriage_profile = '';
        }
        if ($data['has_house'] != $teacher->has_house) {
            $teacher->house_profile = '';
        }
        foreach ($data as $key => $value) {
            $teacher->$key = $value;
        }
        if ($data['marriage'] == 1) {
            $teacher->spouse_name = '';
            $teacher->spouse_unit = '';
        }

        $teacher->updated_at = date('Y-m-d H:i:s', time());
        $teacher->save();
    }

    public static function deleteTeacher($id)
    {
        $teacher = Teacher::where('id', $id)->first();
        $user = User::where('id', $teacher->user_id)->first();
        $user->delete();
        $teacher->delete();
    }

    public static function getTeacherScoreList($id)
    {
        $scores = TeacherScore::where('teacher_id', $id)->get();
        $data = [];
        foreach ($scores as $score) {
            $data[] = [
                'id' => $score->id,
                'key' => $score->key,
                'score' => $score->score,
                'remark' => $score->remark,
                'updated_at' => local_date($score->updated_at, 'Y-m-d H:i:s')
            ];
        }

        return ['rows' => $data];
    }

    public static function saveTeacherScore($data)
    {
        $score = TeacherScore::where('teacher_id', $data['teacher_id'])->where('key', $data['key'])->first();
        if (!$score) {
            $score = new TeacherScore();
            $score->teacher_id = $data['teacher_id'];
            $score->key = $data['key'];
            $score->created_at = date('Y-m-d H:i:s', time());
        }
        $score->score = $data['score'];
        $score->remark = $data['remark'];
        $score->updated_at = date('Y-m-d H:i:s', time());
        $score->save();
        $scores = TeacherScore::where('teacher_id', $data['teacher_id'])->get();
        $num = 0;
        foreach ($scores as $teacherScore) {
            $num += $teacherScore->score;
        }
        $teacher = Teacher::where('id', $data['teacher_id'])->first();
        $teacher->score = $num;
        $teacher->updated_at = date('Y-m-d H:i:s', time());
        $teacher->save();
    }

    public static function getUnitList($limit, $offset, $order)
    {
        $query = Unit::where('status', 1);
        $total = $query->count();
        $units = $query->orderBy('id', $order)->limit($limit)->offset($offset)->get();
        $data = [];
        foreach ($units as $unit) {
            $data[] = [
                'id' => $unit->id,
                'name' => $unit->name
            ];
        }

        return [
            'total'      => $total,
            'rows'       => $data,
            'limit'      => $limit,
            'offset'     => $offset,
            'page'       => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function getUnits()
    {
        $units = Unit::where('status', 1)->get();
        $data = [];
        foreach ($units as $unit) {
            $data[] = [
                'id' => $unit->id,
                'name' => $unit->name
            ];
        }

        return [
            'rows'       => $data,
        ];
    }

    public static function checkTeacher($data)
    {
        $teacher = Teacher::where('id', $data['id'])->first();
        $teacher->status = $data['status'];
        $teacher->updated_at = date('Y-m-d H:i:s', time());
        $teacher->save();
    }

    public static function info($id)
    {
        $user = User::where('id', $id)->first();
        $teacher = Teacher::where('user_id', $user->id)->first();
        if (!$user) {
            return [];
        }

        return [
            'data' => [
                'id' => $user->id,
                'realname' => $user->realname,
                'number' => $user->number,
                'role' => $user->role,
                'role_name' => get_role_name($user->role),
                'status' => $teacher ? $teacher->status : 1
            ]
        ];
    }

    public static function getRoleList($limit, $offset, $order = 'desc', $option = [])
    {
        $query = User::select(['at_user.id', 'at_user.number', 'at_user.realname', 'at_user.role', 'at_teacher.gender'])->leftJoin('at_teacher', 'at_teacher.user_id', 'at_user.id')->where('at_user.status', 1)->where('at_teacher.status', 1);
        if (count($option) && count($option['query'])) {
            foreach ($option['query'] as $search) {
                $query = $query->where('at_user.'.$search['key'], $search['operator'], $search['value']);
            }
        }
        $total = $query->count();
        $roles = $query->limit($limit)->offset($offset)->orderBy('role', $order)->get();
        $data = [];
        foreach ($roles as $role) {
            $data[] = [
                'id' => $role->id,
                'role' => $role->role,
                'number' => $role->number,
                'realname' => $role->realname,
                'gender' => $role->gender
            ];
        }

        return [
            'total' => $total,
            'rows' => $data,
            'limit' => $limit,
            'offset' => $offset,
            'page' => ceil($total / $limit),
            'pageNumber' => $offset / $limit + 1
        ];
    }

    public static function changeUserRole($data)
    {
        $user = User::where('id', $data['id'])->first();
        if ($user->role != $data['role']) {
            $user->role = $data['role'];
            $user->updated_at = date('Y-m-d H:i:s', time());
            $user->save();
        }
    }
}